package com.kim.ping.Service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Service
public class PingService {

    private Logger logger = LoggerFactory.getLogger(PingService.class);

    private WebClient webClient;

    public PingService(){
        this.webClient = WebClient.create("http://localhost:8083");;
    }

    public PingService(WebClient webClient) {
        this.webClient = webClient;
    }

    public void ping(){
        String trackingNumer = getTrackingNumber();
        logger.info(trackingNumer + " start to call pong.");;
        Mono<String> resp = webClient.get()
                .uri("/pong")
                .accept(MediaType.TEXT_PLAIN)
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, clientResponse -> {
                    logger.info(trackingNumer + "Request send & Pong throttled it.");
                    return Mono.empty();
                })
                .bodyToMono(String.class);
        logger.info(trackingNumer + " Request send & Pong response : " + resp.block());;
    }

    public String getTrackingNumber(){
        UUID uuid = UUID.randomUUID();
        return uuid + " - ";
    }
}
